<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
  <script src="/js/axios.min.js"></script>
  <script src="/js/util.js"></script>
<script>
    var id = getQuery("id");
    window.onload=function (){
        findRole();
        findUser();


    }
    function findByGrade(){
        var roleArray = getItem();
        if (roleArray.length ==0){
            $("gradeDiv").innerHTML ="";
            return;
        }
        var params = new URLSearchParams();
        params.append("roleArray",roleArray);
        axios.post("/grade/findByRoleArray",params).then(e=>{
            var info = e.data;
            var str = "";
            for (var i=0;i<info.length;i++){
                str += info[i].grade+",";
            }
            $("gradeDiv").innerHTML = str;
        })
    }
    function getItem(){
        var idArray = [];
        var boxList = document.querySelectorAll(
            "#roleDiv [name='roleArray']:checked"
        );
        for (var i=0;i<boxList.length;i++){
            idArray.push(boxList[i].value);
        }
        return idArray;
    }


     function findUser(){
         axios.get("/user/findById",{
            params:{
                id
            }
        }).then(e=>{
            var info =e.data;
            $("nameSpan").innerHTML = info.name;
            $("accountSpan").innerHTML = info.account;
            var str ="";
            for (var i=0;i<info.gradeList.length;i++){
                str+=`${info.gradeList[i].grade},`
            }
            $("gradeDiv").innerHTML =str;


            for (var i=0;i<info.roleList.length;i++){
                var obj= info.roleList[i];
                document.querySelector("#roleDiv [name='roleArray'][value='"+ obj.id +"']")
                    .checked = true;
            }
        })
    }
    /**
     * 查询角色
     */
    async function findRole(){
        await  axios.get("/role/findAll",null).then(e=>{
            var info = e.data;
            var str = "";
            for (var i=0;i<info.length;i++){
                str+=`<input type='checkbox' name='roleArray' value="${info[i].id}">${info[i].name}`
            }
            $("roleDiv").innerHTML =str;
        });
    }


    function update(){
        var params = new URLSearchParams();
        params.append("id",id);
        params.append("roleArray",getItem());
        axios.post("/user/update",params).then(e=>{
            if (e.data =="ok"){
                location.href="/user/user.html"
            }
        })
    }
</script>
</head>
<body>
    <h2>修改用户权限</h2>
    用户名:<span id="accountSpan"></span><br>
    真实姓名:<spna id="nameSpan"></spna><br>
    拥有角色:<div id="roleDiv" onclick="findByGrade()"></div><br>
    拥有权限:<div id="gradeDiv" ></div>
<input type="button" value="修改" onclick="update()">

<div style="display: none" id="findById">
    角色名称:<span id="name"></span><br>
    拥有权限:<div id="gradeList"></div>

</div>
</body>
</html>